package com.springsecurity.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Entity
@Data
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class User implements UserDetails {
    @Id
    @GeneratedValue (strategy = GenerationType.IDENTITY)
    private  Integer id;
    private  String username;
    private  String password;
    //用户与角色 实现单向多对关系
    @ManyToMany (cascade = CascadeType.MERGE,fetch = FetchType.EAGER)
    private List<Role> roles;
    //重写userDetail的默认方法?
    @Override
    public Collection<?extends GrantedAuthority> getAuthorities(){
        Collection<GrantedAuthority> authorities=new ArrayList<>();
        List<Role> roles =this.getRoles();
        for (Role role :roles){
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        return  authorities;

    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return false;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return false;
    }


    @Override
    public boolean isEnabled(){
        return  true;
    }
}


